﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Data;
using DAL;
using Model;
using Common;

namespace BLL
{
    public class WxUserInfoBLL
    {
        WxUserInfoDAL dal = new WxUserInfoDAL();

        /// <summary>
        /// 根据api获取用户信息
        /// </summary>
        /// <param name="access_token"></param>
        /// <param name="openid"></param>
        /// <returns></returns>
        public wx_userinfo GetWxUserInfo(string access_token,string openid)
        {
            try
            {
                string json = HttpServiceHelper.Get("https://api.weixin.qq.com/cgi-bin/user/info?access_token=" + access_token + "&openid=" + openid + "&lang=zh_CN").Result;
                wx_userinfo model= JSONHelper.DeserializeJsonToObject<wx_userinfo>(json);  
                if(model.openid==null)
                {
                    LogHelper.Error("获取用户信息报错", json);
                    return null;
                }
                else
                {
                    return model;
                }
            }
            catch(Exception e)
            {
                LogHelper.Error(this.GetType().FullName, e.ToString());
                return null;
            }
        }

        /// <summary>
        /// 保存微信用户信息
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public ReturnMessages Add(wx_userinfo model)
        {
            ReturnMessages rm = new ReturnMessages();
            try
            {
                int count = dal.Add(model);
                if (count > 0)
                {
                    rm.code = 200;
                    rm.msg = "add success";
                }
                else
                {
                    rm.code = 400;
                    rm.msg = "add fail";
                }
                return rm;
            }
            catch (Exception e)
            {
                rm.code = 500;
                rm.msg = "server error";
                LogHelper.Error(this.GetType().FullName, e.ToString());
                return rm;
            }
        }

        /// <summary>
        /// 是否存在openid（true表示存在）
        /// </summary>
        /// <param name="openid"></param>
        /// <returns></returns>
        public bool IsExistOpenID(string openid)
        {
            return dal.IsExistOpenID(openid);
        }

        /// <summary>
        /// 更新是否关注标识
        /// </summary>
        /// <param name="openid"></param>
        /// <param name="subscribe"></param>
        /// <returns></returns>
        public ReturnMessages UpdateSubscribe(string openid, int subscribe)
        {
            ReturnMessages rm = new ReturnMessages();
            try
            {
                int count = dal.UpdateSubscribe(openid, subscribe);
                if (count > 0)
                {
                    rm.code = 200;
                    rm.msg = "update success！";
                }
                else
                {
                    rm.code = 400;
                    rm.msg = "update fail";
                }
                return rm;
            }
            catch (Exception e)
            {
                rm.code = 500;
                rm.msg = "server error";
                LogHelper.Error(this.GetType().FullName, e.ToString());
                return rm;
            }
        }

        /// <summary>
        /// 拉取关注用户
        /// </summary>
        /// <returns></returns>
        public ReturnMessages GetOpendIDToUserInfo()
        {
            ReturnMessages rm = new ReturnMessages();
            try
            {
                //获取accesstoken
                accesstoken token = AccessTokenBLL.GetWeiXinModel();
                string json = HttpServiceHelper.Get("https://api.weixin.qq.com/cgi-bin/user/get?access_token=" + token.access_token + "&next_openid=").Result;
                wx_useropenidlist_return model = JSONHelper.DeserializeJsonToObject<wx_useropenidlist_return>(json);
                LogHelper.Info("拉取关注用户-总条数", model.total.ToString());
                int forcount = 1;
                if (model.total > model.count)
                {
                    forcount = (model.total / 10000) + 1;
                }

                List<string> opendid = model.data.openid;
                for (int i = 1; i < forcount; i++)
                {
                    string json_ext = HttpServiceHelper.Get("https://api.weixin.qq.com/cgi-bin/user/get?access_token=" + token.access_token + "&next_openid=" + model.next_openid).Result;
                    wx_useropenidlist_return model_ext = JSONHelper.DeserializeJsonToObject<wx_useropenidlist_return>(json_ext);
                    model.next_openid = model_ext.next_openid;
                    opendid.AddRange(model_ext.data.openid);
                }

                wx_userinfo wxuser = null;
                foreach (var item in opendid)
                {
                    if (!IsExistOpenID(item))
                    {
                        //获取用户信息
                        wxuser = GetWxUserInfo(token.access_token, item);
                        if (wxuser != null)
                        {
                            Add(wxuser);
                        }
                        else
                        {
                            //说明获取数据报错，跳出循环
                            break;
                        }
                    }
                }
                return rm;
            }
            catch (Exception e)
            {
                rm.code = 500;
                rm.msg = "server error";
                LogHelper.Error(this.GetType().FullName, e.ToString());
                return rm;
            }
        }

    }
}
